<?php
/**
  * Note: change method from get to post, we must change all get(keyword) in header_home, header, and column_left_search
 * controller
**/

class ControllerProductSearch extends Controller { 	
	public function index() {    
    	$this->language->load('product/search');
    	$this->data['template'] = $this->config->get('config_template');   
	  	  
    	if (isset($this->request->post['keyword'])) {
            $search_keyword = $this->request->post['keyword'];
    		$this->document->title = $this->language->get('heading_title') .  ' - ' . $search_keyword;
		}
        elseif (isset($this->request->get['keyword'])) {
            $search_keyword = $this->request->get['keyword'];
            $this->document->title = $this->language->get('heading_title') .  ' - ' . $search_keyword;
        }
        else {
			$this->document->title = $this->language->get('heading_title');
            $search_keyword = null;
		}

		$this->document->breadcrumbs = array();

   		$this->document->breadcrumbs[] = array( 
       		'href'      => HTTP_SERVER . 'index.php?route=common/home',
       		'text'      => $this->language->get('text_home'),
      		'separator' => FALSE
   		);
				
		$url = '';  		
		if ($search_keyword) {
			$url .= '&keyword=' . $search_keyword;
		}       		
		if (isset($this->request->get['category_id'])) {
			$url .= '&category_id=' . $this->request->get['category_id'];
		}    		
		if (isset($this->request->get['description'])) {
			$url .= '&description=' . $this->request->get['description'];
		}    		
		if (isset($this->request->get['model'])) {
			$url .= '&model=' . $this->request->get['model'];
		}   
		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}	 
		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}   				
		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}	
        			
   		$this->document->breadcrumbs[] = array(
       		'href'      => HTTP_SERVER . 'index.php?route=product/search' . $url,
       		'text'      => $this->language->get('heading_title'),
      		'separator' => $this->language->get('text_separator')
   		);
		
    	$this->data['heading_title'] = $this->language->get('heading_title');
   
    	$this->data['text_critea'] = $this->language->get('text_critea');
    	$this->data['text_search'] = $this->language->get('text_search');
		$this->data['text_keyword'] = $this->language->get('text_keyword');
		$this->data['text_category'] = $this->language->get('text_category');
		$this->data['text_empty'] = $this->language->get('text_empty');
		$this->data['text_sort'] = $this->language->get('text_sort');
        $this->data['text_size'] = $this->language->get('text_size');
			 
		$this->data['entry_search'] = $this->language->get('entry_search');
    	$this->data['entry_description'] = $this->language->get('entry_description');
		$this->data['entry_model'] = $this->language->get('entry_model');
		  
    	$this->data['button_search'] = $this->language->get('button_search');
   
  		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			//$sort = 'p.sort_order';
            //$sort = 'pcs.product_sort_order';
            $sort = 'pd.name';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}
		
		if ($search_keyword) {
			//$this->data['keyword'] = $search_keyword;
            $this->data['keyword'] = html_entity_decode($search_keyword, ENT_COMPAT, 'UTF-8');
		} else {
			$this->data['keyword'] = '';
		}     
            
        $url = '';                    
        if ($search_keyword) {
            $url .= '&keyword=' . $search_keyword;
        }                 
        $url .= '&sort=' . $sort . '&order=' . $order;
                                                                
        $this->load->model('catalog/attribute');
        $attributes = array();
        $attributes[] = array(
            'name'              => '-- None --',
            'sort_order'        => 0,
            'attribute_id'      => 0,
            'items'             => array(),
            'href'              => HTTP_SERVER . 'index.php?route=product/search' . $url,
        );    
        $attribute_data = $results = $this->model_catalog_attribute->getNormalAttributes();              
        foreach($attribute_data as $attribute_item){
            $attributes[] = array(
                'name'              => $attribute_item['name'],
                'sort_order'        => $attribute_item['sort_order'],
                'attribute_id'      => $attribute_item['attribute_id'],
                'items'             => $this->model_catalog_attribute->getAttributeValues($attribute_item['attribute_id']),                
                'href'              => HTTP_SERVER . 'index.php?route=product/search' . $url . '&attribute[][' . $attribute_item['attribute_id'] . ']=',                
            );    
        }
        $this->data['attributes'] = $attributes;
        if (isset($this->request->get['attribute'])) {
            $this->data['selected_attribute'] = $this->request->get['attribute'];
        } 
        else {
            $this->data['selected_attribute'] = array();
        }     
                
		$limit = 9; //24; //12;
        $this->data['products'] = array();
		/*
		if (isset($this->request->get['category_id'])) {
			$this->data['category_id'] = $this->request->get['category_id'];
		} else {
			$this->data['category_id'] = '';
		}

		$this->load->model('catalog/category');
		
		$this->data['categories'] = $this->getCategories(0);
		
		if (isset($this->request->get['description'])) {
			$this->data['description'] = $this->request->get['description'];
		} else {
			$this->data['description'] = '';
		}
		
		if (isset($this->request->get['model'])) {
			$this->data['model'] = $this->request->get['model'];
		} else {
			$this->data['model'] = '';
		}
		*/
		
		if ($search_keyword) {
			$this->load->model('catalog/product');             
            $keyword = html_entity_decode($search_keyword, ENT_COMPAT, 'UTF-8');

			/*
            $attribute_ids = array();
            if(isset($this->request->get['attribute']) && is_array($this->request->get['attribute'])){
                $attribute_ids = $this->request->get['attribute'];
            }
            $selected_values = array();   
            $attribute_list = array(); 
            $attr_list = ''; 
            foreach($attribute_ids as $attribute_id){        
                foreach($attribute_id as $key => $val){                                
                    $attribute_list[] = $key;
                    $selected_values[] = $val;
                    $attr_list .= '&attribute[][' . $key . ']=' . $val; 
                }
            }
            $attribute_list = array_unique($attribute_list);
            
			//$product_total = $this->model_catalog_product->getTotalProductsByKeyword($search_keyword, isset($this->request->get['category_id']) ? $this->request->get['category_id'] : '', isset($this->request->get['description']) ? $this->request->get['description'] : '', isset($this->request->get['model']) ? $this->request->get['model'] : '');
			//$product_tag_total = $this->model_catalog_product->getTotalProductsByTag($search_keyword, isset($this->request->get['category_id']) ? $this->request->get['category_id'] : '');
			//$product_total = max($product_total, $product_tag_total);
			if ($attribute_list){
                $product_total = $this->model_catalog_product->getTotalProductsByKeywordAttribute($keyword, $attribute_list, $selected_values);
            }
            else{ 
                $product_total = $this->model_catalog_product->getTotalProductsByKeyword($keyword);
            }
			*/ 
			
			$attr_list = '';
			$product_total = $this->model_catalog_product->getTotalProductsByKeyword($keyword);			
			if ($product_total) {	    
				/*			
				$url = '';    
				if (isset($this->request->get['category_id'])) {
					$url .= '&category_id=' . $this->request->get['category_id'];
				}   		
				if (isset($this->request->get['description'])) {
					$url .= '&description=' . $this->request->get['description'];
				}    				
				if (isset($this->request->get['model'])) {
					$url .= '&model=' . $this->request->get['model'];
				}
				*/
				$this->load->model('catalog/category');
				$this->load->model('catalog/review');
				$this->load->model('tool/seo_url'); 
				$this->load->model('tool/image');
                $this->load->model('catalog/discount');  
				
				$this->data['button_add_to_cart'] = $this->language->get('button_add_to_cart'); 
				
				/*
				$results = $this->model_catalog_product->getProductsByKeyword($search_keyword, isset($this->request->get['category_id']) ? $this->request->get['category_id'] : '', isset($this->request->get['description']) ? $this->request->get['description'] : '', isset($this->request->get['model']) ? $this->request->get['model'] : '', $sort, $order, ($page - 1) * $this->config->get('config_catalog_limit'), $this->config->get('config_catalog_limit'));
        		$tag_results = $this->model_catalog_product->getProductsByTag($search_keyword, isset($this->request->get['category_id']) ? $this->request->get['category_id'] : '', $sort, $order, ($page - 1) * $this->config->get('config_catalog_limit'), $this->config->get('config_catalog_limit'));
        		foreach ($results as $key => $value) {
					$tag_results[$value['product_id']] = $results[$key];
				}
				//$product_total = count($tag_results);				
				
                if ($attribute_list){ 
                    //$results = $this->model_catalog_product->searchProductsByAttribute($search_keyword, $this->request->get['attribute'], $sort, $order, ($page - 1) * $limit, $limit);
                    $results = $this->model_catalog_product->searchProductsByAttribute($keyword, $attribute_list, $selected_values, $sort, $order, ($page - 1) * $limit, $limit);
                }
                else{
        		    //$results = $this->model_catalog_product->searchProducts($search_keyword, $sort, $order, ($page - 1) * $limit, $limit);
                    $results = $this->model_catalog_product->searchProducts($keyword, $sort, $order, ($page - 1) * $limit, $limit);
                }
				*/
				
				$results = $this->model_catalog_product->searchProducts($keyword, $sort, $order, ($page - 1) * $limit, $limit);
				foreach ($results as $result) {
        			if ($result['image']) {
						$image = $result['image'];
					} else {
						$image = 'no_image.jpg';
					}						
					
					if ($this->config->get('config_review')) {
						$rating = $this->model_catalog_review->getAverageRating($result['product_id']);	
					} else {
						$rating = false;
					}
					
                    /*
					$special = FALSE; 					
					$discount = $this->model_catalog_product->getProductDiscount($result['product_id']);
 					
					if ($discount) {
						$price = $this->currency->formatPrice($this->tax->calculate($discount, $result['tax_class_id'], $this->config->get('config_tax')));
					} else {
						$price = $this->currency->formatPrice($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
					
						$special = $this->model_catalog_product->getProductSpecial($result['product_id']);
					
						if ($special) {
							$special = $this->currency->formatPrice($this->tax->calculate($special, $result['tax_class_id'], $this->config->get('config_tax')));
						}					
					}
					*/
                     
                    $price = $result['price'];
                    $price_fomatted = $this->currency->formatPrice($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
                    $discount = 0;
                    $discount_formatted = 0;
                    $discount_data = $this->model_catalog_discount->getDiscount($result['product_id']); 
                    if($discount_data > 0){
                        $discount = $discount_data;
                        $discount_formatted = $this->currency->formatPrice($this->tax->calculate($discount_data, $result['tax_class_id'], $this->config->get('config_tax'))); 
                    }
                    
                    $discounts_data = $this->model_catalog_product->getProductDiscounts($result['product_id']);                                                     
                    if($discounts_data){  
                        $discount = $discounts_data[0]['price'];
                        $discount_formatted = $this->currency->formatPrice($this->tax->calculate($discounts_data[0]['price'], $result['tax_class_id'], $this->config->get('config_tax')));                    
                    }                         
                    
                    $special = false;
                       
					//$options = $this->model_catalog_product->getProductOptions($result['product_id']);
					$options = $this->model_catalog_product->getActiveProductOptions($result['product_id']);
                    $attribute_price = 0;
                    $min_price = false;   
                    $price_ref = $discount ? $discount : $price;
                    foreach($options as $option_item){
                        foreach($option_item['option_value'] as $option_value){ 
                            $option_price = (float)$option_value['price'] ? $this->tax->calculate($option_value['price'], $result['tax_class_id'], $this->config->get('config_tax')) : 0;                    
                            if($option_price && ($option_value['prefix'] == '-')){
                                $option_price = -1 * $option_price;                        
                            }
                            
                            if($option_price < $attribute_price){
                                $attribute_price = $option_price;   
                            }
                            
                            if($option_price > 0){
                                $min_price = true;
                            }
                        }
                    }                
                
					if ($options) {
						$add = $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/product&product_id=' . $result['product_id']);
					} else {
						$add = HTTPS_SERVER . 'index.php?route=checkout/cart&product_id=' . $result['product_id'];
					}
					  
					$path = $this->model_catalog_product->getCategoriesPath($result['product_id']);			
					$url = HTTP_SERVER . 'index.php?route=product/product&path=' . $path . '&product_id=' . $result['product_id'] . '&keyword=' . $search_keyword;
                    
                    if($attribute_price != 0){
                        $ref_price =  $this->currency->formatPrice($price_ref + $attribute_price);
                    }
                    elseif($min_price){
                        $ref_price = $this->currency->formatPrice($price_ref);    
                    }
                    else{
                        $ref_price = 0;
                    }

                    $rate_discount = ((floatval($price) - floatval($price_ref)) / floatval($price)) * 100;
                    $rate_discount = round($rate_discount);

					//$shortname = (strlen($result['name']) < 16) ? $result['name'] : substr($result['name'], 0 ,16) . ' ...';					
                    $shortname = $this->model_catalog_product->breakProductName($result['name'], 34); 

                    $this->data['products'][] = array(
            			'name'    	=> $result['name'],
            			'shortname' => $shortname,
						'model'   	=> $result['model'],
						'rating'  	=> $rating,
						'stars'   	=> sprintf($this->language->get('text_stars'), $rating),
            			//'thumb'     => $this->model_tool_image->resize($image, 121, 148),
                        'thumb'     => $this->model_tool_image->resize($image, 190, 230),
            			'price'  	=> $price_fomatted,
                        'discount'  => $discount_formatted, 
                        'ref_price' => $ref_price,
            			'options' 	=> $options,
						'special' 	=> $special,
						'href'    	=> $this->model_tool_seo_url->rewrite($url),
						'add'	  	=> $add,
						'sku'	  	=> $result['sku'],
                        'unbreak'   => mb_strlen($shortname, 'UTF-8') <= 34,
                        'rate_discount' => $rate_discount,
          			);           			
        		}
				 
				if (!$this->config->get('config_customer_price')) {
					$this->data['display_price'] = TRUE;
				} elseif ($this->customer->isLogged()) {
					$this->data['display_price'] = TRUE;
				} else {
					$this->data['display_price'] = FALSE;
				}    
        
				$url = HTTP_SERVER . 'index.php?route=product/search';    				
				if ($search_keyword) {
					$url .= '&keyword=' . $search_keyword;
				} 	
				/*			
				if (isset($this->request->get['category_id'])) {
					$url .= '&category_id=' . $this->request->get['category_id'];
				} 				
				if (isset($this->request->get['description'])) {
					$url .= '&description=' . $this->request->get['description'];
				}
				
				if (isset($this->request->get['model'])) {
					$url .= '&model=' . $this->request->get['model'];
				}
                */
                if ($attr_list) {
                    $url .= $attr_list;
                } 
				if (isset($this->request->get['page'])) {
					$url .= '&page=' . $this->request->get['page'];
				}					  
                  
				$this->data['sorts'] = array();	
                /*			
				$this->data['sorts'][] = array(
					'text'  => $this->language->get('text_default'),
					//'value' => 'p.sort_order-ASC',
                    'value' => 'pcs.product_sort_order-ASC', 
					//'href'  => HTTP_SERVER . 'index.php?route=product/search' . $url . '&sort=p.sort_order&order=ASC'
                    'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=pcs.product_sort_order&order=ASC'),  
				);  	
                */	
                $this->data['sorts'][] = array(
                    'text'  => $this->language->get('text_name_asc'),
                    'value' => 'pd.name-ASC',
                    'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=pd.name&order=ASC'),
                );
                $this->data['sorts'][] = array(
                    'text'  => $this->language->get('text_name_desc'),
                    'value' => 'pd.name-DESC',
                    'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=pd.name&order=DESC'),
                );  		
                $this->data['sorts'][] = array(
                    'text'  => $this->language->get('text_newest'),
                    'value' => 'p.date_added-DESC',
                    'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=p.date_added&order=DESC'),
                );   
				$this->data['sorts'][] = array(
					'text'  => $this->language->get('text_price_asc'),
					'value' => 'p.price-ASC',
					'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=p.price&order=ASC'),
				); 
				$this->data['sorts'][] = array(
					'text'  => $this->language->get('text_price_desc'),
					'value' => 'p.price-DESC',
					'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=p.price&order=DESC'),
				);
                /*
                $this->data['sorts'][] = array(
                    'text'  => $this->language->get('text_category_asc'),
                    'value' => 'cd.name-ASC',
                    'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=cd.name&order=ASC'),
                );
                $this->data['sorts'][] = array(
                    'text'  => $this->language->get('text_manufacture_asc'),
                    'value' => 'm.name-ASC',
                    'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=m.name&order=ASC')
                ); 
				*/  
				/*
				$this->data['sorts'][] = array(
					'text'  => $this->language->get('text_rating_desc'),
					'value' => 'rating-DESC',
					'href'  => HTTP_SERVER . 'index.php?route=product/search' . $url . '&sort=rating&order=DESC'
				); 
				
				$this->data['sorts'][] = array(
					'text'  => $this->language->get('text_rating_asc'),
					'value' => 'rating-ASC',
					'href'  => HTTP_SERVER . 'index.php?route=product/search' . $url . '&sort=rating&order=ASC'
				);
				
				$this->data['sorts'][] = array(
					'text'  => $this->language->get('text_model_asc'),
					'value' => 'p.model-ASC',
					'href'  => HTTP_SERVER . 'index.php?route=product/search' . $url . '&sort=p.model&order=ASC'
				); 

				$this->data['sorts'][] = array(
					'text'  => $this->language->get('text_model_desc'),
					'value' => 'p.model-DESC',
					'href'  => HTTP_SERVER . 'index.php?route=product/search' . $url . '&sort=p.model&order=DESC'
				);
				*/
				
				$url = '';   
				if ($search_keyword) {
					$url .= '&keyword=' . $search_keyword;
				}
				/*
				if (isset($this->request->get['category_id'])) {
					$url .= '&category_id=' . $this->request->get['category_id'];
				}
				
				if (isset($this->request->get['description'])) {
					$url .= '&description=' . $this->request->get['description'];
				}
				
				if (isset($this->request->get['model'])) {
					$url .= '&model=' . $this->request->get['model'];
				}
				*/
				if (isset($this->request->get['sort'])) {
					$url .= '&sort=' . $this->request->get['sort'];
				}	

				if (isset($this->request->get['order'])) {
					$url .= '&order=' . $this->request->get['order'];
				}
				 
				$pagination = new Pagination();
				$pagination->total = $product_total;
				$pagination->page = $page;
				$pagination->limit = $limit;
				$pagination->text = $this->language->get('text_pagination');
				$pagination->url = $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/search' . $url . '&page={page}');				
				$this->data['pagination'] = $pagination->renderPaging();   
				
				$this->data['sort'] = $sort;
				$this->data['order'] = $order;      
			}
		}

        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/search.tpl')) {
            $this->template = $this->config->get('config_template') . '/template/product/search.tpl';
        }
        else {
            $this->template = 'default/template/product/search.tpl';
        }
		
		$this->children = array(
			//'common/column_right',
			//'common/column_left_search',
			'common/column_left',
			'common/footer',
			'common/header',
            'module/category',
            'module/services',
            'module/newsletter',
		);

        $this->data['lazy_load'] = array(
            'total'     => $pagination->total,
            'page'      => $pagination->page,
            'limit'     => $pagination->limit,
            'url'       => $pagination->url,
        );
        if (isset($this->request->get['lazy_load']) && $this->request->get['lazy_load']) {
            if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/category_lazyload.tpl')) {
                $this->template = $this->config->get('config_template') . '/template/product/category_lazyload.tpl';
            }
            else {
                $this->template = $this->config->get('config_template') . '/template/product/search.tpl';
            }
        }

		$this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
  	}
	
	private function getCategories($parent_id, $level = 0) {
		$level++;
		
		$data = array();
		
		$results = $this->model_catalog_category->getCategories($parent_id);
		
		foreach ($results as $result) {
			$data[] = array(
				'category_id' => $result['category_id'],
				'name'        => str_repeat('&nbsp;&nbsp;&nbsp;', $level) . $result['name']
			);
			
			$children = $this->getCategories($result['category_id'], $level);
			
			if ($children) {
			  $data = array_merge($data, $children);
			}
		}
		
		return $data;
	}	
}
?>